﻿using System.Reflection;

namespace Core.Extensions
{
    public static class ConvertExtensions
    {
        public static List<T> StringSplitGetList<T>(this string source)
        {
            if (string.IsNullOrEmpty(source))
                return new List<T>();
            Type tp = typeof(T);
            List<T> res = new();
            var ids = source.Split(",");
            if (tp.Name.ToLower() == "string")
            {
                foreach (var id in ids ?? Enumerable.Empty<string>())
                {
                    res.Add((T)(id as object));
                }
            }
            else
            {
                var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, new Type[] { typeof(string), tp.MakeByRefType() }, new ParameterModifier[] { new ParameterModifier(2) });
                foreach (var id in ids ?? Enumerable.Empty<string>())
                {
                    var parameters = new object[] { id, Activator.CreateInstance(tp) };
                    if ((bool)TryParse.Invoke(null, parameters))
                    {
                        res.Add((T)parameters[1]);
                    }
                }
            }
            return res;
        }
    }
}
